<template>
	<view class="tabs">
		<!-- tab 列表 -->
		<view class="tab-list" ref="tabListRef">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :style="{
          color: index === activeIndex ? activeColor : inactiveColor,
          fontSize: fontSize + 'rpx',
		  paddingTop: paddingTopValue + 'rpx',
		  paddingBottom: paddingBottomValue + 'rpx'
		  
        }" @click="changeTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- 下滑块 -->
		<view class="slider" :style="{
        width: sliderWidth + 'rpx',
        backgroundColor: sliderColor,
        transform: 'translateX(' + sliderLeft + 'px)'
      }"></view>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		onMounted,
		nextTick,
		getCurrentInstance
	} from 'vue'

	// Props
	const props = defineProps({
		tabs: {
			type: Array,
			default: () => ['选项一', '选项二']
		},
		activeIndex: {
			type: Number,
			default: 0
		},
		activeColor: {
			type: String,
			default: '#007AFF'
		},
		inactiveColor: {
			type: String,
			default: '#666'
		},
		sliderColor: {
			type: String,
			default: '#007AFF'
		},
		sliderWidth: {
			type: Number,
			default: 40 // 滑块宽度 (rpx)
		},
		fontSize: {
			type: Number,
			default: 28 // 字体大小 (rpx)
		},
		paddingTopValue: {
			type: Number,
			default: 10 // 上下内边框大小 (rpx)  ，会影响到tabs的高度
		},
		paddingBottomValue: {
			type: Number,
			default: 10 // 上下内边框大小 (rpx)  ，会影响到tabs的高度
		}
	})

	// Emits
	const emit = defineEmits(['update:activeIndex'])

	// 当前选中
	const activeIndex = ref(props.activeIndex)

	// 滑块位置
	const sliderLeft = ref(0)

	// tab 宽度
	const tabWidth = ref(0)
	const tabListRef = ref(null)

	const instance = getCurrentInstance()

	onMounted(() => {
		nextTick(() => {
			// 判断环境
			let context
			if (typeof uni !== 'undefined' && uni.createSelectorQuery) {
				// 小程序环境
				context = instance?.ctx || instance
			} else {
				// H5 或其他环境
				context = instance?.proxy
			}
			const query = uni.createSelectorQuery().in(context)
			query.select('.tab-list')
				.boundingClientRect(res => {
					if (res) {
						tabWidth.value = res.width / props.tabs.length
						updateSlider()
					}
				})
				.exec()
		})
	})




	watch(activeIndex, () => {
		updateSlider()
	})

	// 更新滑块位置
	const updateSlider = () => {
		sliderLeft.value =
			tabWidth.value * activeIndex.value + (tabWidth.value - uni.upx2px(props.sliderWidth)) / 2
	}

	// 切换 tab
	const changeTab = (index) => {
		activeIndex.value = index
		emit('update:activeIndex', index)
	}
</script>

<style scoped>
	.tabs {
		position: relative;
		width: 100%;
	}

	.tab-list {
		display: flex;
		justify-content: space-around;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		box-sizing: border-box;

	}

	.slider {
		height: 6rpx;
		border-radius: 3rpx;
		position: absolute;
		bottom: 0;
		transition: transform 0.3s;
	}
</style>